//
//  AppDelegate.m
//  RunLoop
//
//  Created by QDSG on 2019/6/14.
//  Copyright © 2019 unitTao. All rights reserved.
//

#import "AppDelegate.h"

@interface AppDelegate ()

@property (nonatomic, assign) UIBackgroundTaskIdentifier bgTaskIdentifier;

@property (nonatomic, assign) BOOL isFinished;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

- (void)myTask {
    __block int i = 1;
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        NSLog(@"i = %d", i);
        i++;
        if (i > 2 * 60) {
            self.isFinished = YES;
            dispatch_source_cancel(timer);
        }
    });
    dispatch_resume(timer);
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    NSLog(@"app did enter background.");
    
    [self myTask];
    
    self.bgTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{
        NSLog(@"结束后台任务");
        NSLog(@"线程堆栈信息：%@", [NSThread callStackSymbols]);
        [application endBackgroundTask:self.bgTaskIdentifier];
        self.bgTaskIdentifier = UIBackgroundTaskInvalid;
        
        if (self.isFinished) {
            NSLog(@"任务完成");
        } else {
            NSLog(@"任务未完成");
        }
    }];
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
